<template>
  <div class="content">
    <!-- 左侧表达 -->
    <div class="m-form-box">
      <el-form :label-position="'right'" label-width="120px" :model="form_data">
        <el-form-item label="选择表">
          <el-select
            filterable
            v-model="table_select_val"
            @change="select_change"
            placeholder="请选择"
          >
            <el-option
              v-for="item in tableArr"
              :key="item.value"
              :label="item.label"
              :value="item.label"
            ></el-option>
          </el-select>
        </el-form-item>
        <div v-for="(value, key, index) in form_data.form_input" :key="index">
          <el-form-item :label="key" v-if="hiddenId != isHidden[key]">
            <el-select
              v-if="setArr(key) && setArr(key, 1) == 'sql_query'"
              v-model="form_data.form_input[key]"
              filterable
              placeholder="请选择"
            >
              <el-option
                v-for="item in setArr(key)"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
            <div v-else-if="setArr(key) && setArr(key, 1) == 'nice_enum'">
              <el-popover placement="right" width="400" trigger="click">
                <el-tree
                  :data="setArr(key)"
                  @node-click="handleNodeClick($event, key)"
                ></el-tree>
                <span slot="reference" class="u-tree-box">
                  <span v-if="form_data.form_input[key]"
                    >Id - {{ form_data.form_input[key] }}</span
                  >
                  <a>{{ treeVal }}</a>
                </span>
              </el-popover>
            </div>
            <el-input v-else v-model="form_data.form_input[key]"></el-input>
          </el-form-item>
        </div>

        <el-form-item>
          <el-dropdown
            split-button
            type="primary"
            @click="insertUpdateTable(btnArr[0])"
          >
            {{ btnArr[0] }}
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item
                v-for="(item, index) in btnArr"
                :key="index"
                @click.native="insertUpdateTable(item)"
                >{{ item }}</el-dropdown-item
              >
            </el-dropdown-menu>
          </el-dropdown>
          <!-- <el-button type="primary" @click="insertUpdateTable">插入</el-button> -->
          <el-button @click="clearForm">清空</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 对应表内数据查看 -->
    <div class="m-table-box">
      <h1>表内数据</h1>
      <el-table
        v-if="tableData && tableData.length > 0"
        v-loading="dataListLoading"
        :data="tableData"
        height="65vh"
        style="width: 100%"
        header-cell-class-name="thead"
      >
        <el-table-column
          v-for="(item, index) in colArr"
          :key="index"
          :prop="item"
          :label="item"
        ></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="updateData(scope.row)"
              >修改</el-button
            >
            <el-button
              type="text"
              size="small"
              @click="delectTableData(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="u-null" v-else>该表尚未完善</div>
      <el-pagination
        @size-change="sizeChangeHandle"
        @current-change="currentChangeHandle"
        :current-page="pageIndex"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        :total="totalPage"
        layout="total, sizes, prev, pager, next, jumper"
      ></el-pagination>
    </div>
  </div>
</template>

<script>
import {
  tableInsert,
  tableUpdate,
  tableDeleted,
  queryPageList,
  listFieldsAndProertiesByTableName,
  listByCols,
  getFiledsDataByTableName
} from '@/api/api.js'
export default {
  data () {
    return {
      treeVal: '未选择',
      hiddenId: '',
      selectArr: {},
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      colArr: [],
      tableData: [],
      btnArr: ['插入', '修改'],
      table_select_val: 'core_table',
      tableArr: [
        {
          value: 'core_table',
          label: 'core_table'
        },
        {
          value: 'core_table_and_field',
          label: 'core_table_and_field'
        },
        {
          value: 'core_property',
          label: 'core_property'
        },
        {
          value: 'core_property_value',
          label: 'core_property_value'
        },
        {
          value: 'core_property_group',
          label: 'core_property_group'
        },
        {
          value: 'core_property_group_and_property',
          label: 'core_property_group_and_property'
        }
      ],
      // form_obj: [
      //   {
      //     table_name: 'core_table',
      //     form_input: { table_id: '', table_name: '', description: '' }
      //   },
      //   {
      //     table_name: 'core_table_and_field',
      //     form_input: {
      //       field_id: '',
      //       table_id: '',
      //       field_name: '',
      //       property_group_ids: '',
      //       description: ''
      //     }
      //   },
      //   {
      //     table_name: 'core_property',
      //     form_input: {
      //       property_id: '',
      //       property_name: '',
      //       description: '',
      //       life_cycle: '',
      //       related_operation: ''
      //     }
      //   },
      //   {
      //     table_name: 'core_property_value',
      //     form_input: {
      //       property_value_id: '',
      //       property_id: '',
      //       property_value: '',
      //       description: '',
      //       handle_class: ''
      //     }
      //   },
      //   {
      //     table_name: 'core_property_group',
      //     form_input: {
      //       property_group_id: '',
      //       property_group_name: '',
      //       description: ''
      //     }
      //   },
      //   {
      //     table_name: 'core_property_group_and_property',
      //     form_input: {
      //       t_id: '',
      //       property_group_id: '',
      //       property_id: '',
      //       property_value_id: '',
      //       property_value_param: '',
      //       description: ''
      //     }
      //   }
      // ],
      labelPosition: 'right',
      isHidden: {},
      form_data: {
        // table_name: 'core_table_and_member',
        table_name: 'core_table',
        table_id: '1',
        form_input: { table_id: '', table_name: '', description: '' }
      }
    }
  },
  activated () {
    if (this.$route.query.tableName) {
      this.$route.query.tableName = this.table_select_val = this.$route.query.tableName
    }
    this.getHidden()
    this.getTableArr()
    this.select_change(this.table_select_val)
  },
  // mounted () {
  //   if (this.$route.query.tableName) {
  //     this.$route.query.tableName = this.table_select_val = this.$route.query.tableName
  //   }
  //   this.getTableArr()
  //   this.select_change(this.table_select_val)
  // },
  methods: {
    handleNodeClick (data, key) {
      this.treeVal = data.label
      this.form_data.form_input[key] = data.value
    },
    setArr (e, type) {
      if (type) {
        return this.selectArr[e].type
      }
      if (this.selectArr[e]) {
        let arr = this.selectArr[e].data
        if (arr.constructor === Array) {
          return arr
        } else {
          return [arr]
        }
      } else {
        return false
      }
    },
    // 获取下拉菜单数据
    async getSelectData () {
      let res = await getFiledsDataByTableName({
        tableName: this.form_data.table_name,
        fields: []
      })
      if (res[0]) {
        return
      }
      console.log(res[1], '12312312')
      let arr = res[1].data
      arr.map(item => {
        if (item.sourceType === 'sql_query') {
          this.selectArr[item.fieldName] = {
            data: item.sourceData,
            type: 'sql_query'
          }
        } else if (item.sourceType === 'nice_enum') {
          this.selectArr[item.fieldName] = {
            data: item.sourceData,
            type: 'nice_enum'
          }
        }
      })
      // Object.keys(this.selectArr).forEach(item => {
      //   for (let i = 0; i < arr.length; i++) {
      //     if (arr[i].fieldName === item) {
      //       this.selectArr[item] = arr[i].child
      //     }
      //   }
      // })
      console.log(this.selectArr)
      this.selectArr = JSON.parse(
        JSON.stringify(this.selectArr)
          .split('display_value')
          .join('label')
          .split('child')
          .join('children')
          .split('t_id')
          .join('value')
      )
    },
    // 获取需要隐藏的表单
    async getHidden () {
      let res = await queryPageList({
        table_name: 'core_property_value',
        currPage: 1,
        pageSize: 9999
        // property_id: 1
      })
      if (res[0]) {
        return
      }

      res[1].page.list.map(item => {
        if (item.property_value === 'hidden_input') {
          this.hiddenId = item.property_value_id
        }
      })
    },
    // 获取下拉菜单
    async getTableArr () {
      let res = await listByCols()
      if (res[0]) {
        return
      }
      let arr = res[1].data
      this.tableArr = []
      arr.map(item => {
        this.tableArr.push({
          value: item.tableId,
          label: item.tableName
        })
      })

      //
    },
    select_change (e) {
      this.pageIndex = 1
      this.btnArrChange('插入')
      this.form_data.table_name = e
      // this.form_data.table_id = e
      this.getSelectData()
      this.queryPageList()
      this.treeVal = '未选择'
    },

    // 删除某表格内数据
    async delectTableData (e) {
      let where = {}
      where[this.colArr[0]] = JSON.stringify([e[this.colArr[0]]])
      let res = await tableDeleted([
        {
          table_name: this.form_data.table_name,
          where: where
        }
      ])
      if (res[0]) {
        return
      }
      this.queryPageList()
    },
    // 查询对应表的数据
    async queryPageList () {
      let res = await queryPageList({
        table_name: this.form_data.table_name,
        currPage: this.pageIndex,
        pageSize: this.pageSize
        // property_id: 1
      })
      if (res[0]) {
        return
      }

      if (this.pageIndex === 1) {
        let res2 = await listFieldsAndProertiesByTableName({
          tableName: this.form_data.table_name
        })
        if (res[0]) {
          return
        }
        let obj = {}
        this.colArr = []
        this.isHidden = {}
        res2[1].data.map(item => {
          this.colArr.push(item.fieldName)
          this.isHidden[item.fieldName] = ''
          if (item.fieldPropertys && item.fieldPropertys.length > 0) {
            item.fieldPropertys.map(item2 => {
              if (this.hiddenId === item2.propertyValueId) {
                this.isHidden[item.fieldName] = this.hiddenId
              }
            })
          }
        })
        console.log(this.isHidden, 'this.isHiddenthis.isHidden')
        // for (let item in res2[1].data) {
        //   this.colArr.push(item.fieldName)
        // }
        for (let i = 0; i < this.colArr.length; i++) {
          obj[this.colArr[i]] = ''
          // if (e === this.form_obj[i].table_name) {
          //   this.form_data = this.form_obj[i]
          // }
        }
        this.form_data.form_input = JSON.parse(JSON.stringify(obj))
        this.tableData = res[1].page.list
        this.totalPage = res[1].page.totalCount
      } else {
        this.tableData = res[1].page.list
        this.totalPage = res[1].page.totalCount
      }
      // this.form_data.form_input = obj
      // this.tableData = []
      // this.totalPage = 0
    },
    // 插入修改表格数据接口
    async insertUpdateTable (e) {
      if (e === '插入') {
        // 插入
        let res = await tableInsert([
          {
            table_name: this.form_data.table_name,
            list: [this.form_data.form_input]
          }
        ])
        if (res[1].code === 0) {
          this.$message({
            message: '插入数据成功',
            type: 'success'
          })
          this.queryPageList()
          this.clearForm()
          this.treeVal = '未选择'
        } else {
          this.$message(res[1].msg)
        }
      } else {
        // 修改
        let where = [{}]
        where[0][this.colArr[0]] = this.form_data.form_input[this.colArr[0]]

        let res = await tableUpdate([
          {
            table_name: this.form_data.table_name,
            update: [this.form_data.form_input],
            where: where
          }
        ])
        if (res[1].code === 0) {
          this.$message({
            message: '修改数据成功',
            type: 'success'
          })
          this.clearForm()
          this.queryPageList()
          this.treeVal = '未选择'
        } else {
          this.$message(res[1].msg)
        }
      }
    },
    updateData (e) {
      for (let item in this.form_data.form_input) {
        this.form_data.form_input[item] = e[item]
      }
      this.btnArrChange('修改')
      this.treeVal = '未选择'
    },

    // 修改form赋值
    btnArrChange (e) {
      if (e === '修改') {
        if (this.btnArr[0] === e) {
          return
        }
        let changeBtn = this.btnArr[1]
        this.btnArr.splice(1, 1)
        this.btnArr.unshift(changeBtn)
      } else {
        if (this.btnArr[0] === e) {
          return
        }
        let changeBtn = this.btnArr[1]
        this.btnArr.splice(1, 1)
        this.btnArr.unshift(changeBtn)
      }
    },
    // 重置form
    clearForm () {
      for (let item in this.form_data.form_input) {
        this.form_data.form_input[item] = ''
      }
    },
    // 每页数
    sizeChangeHandle (val) {
      this.pageSize = val
      this.pageIndex = 1
      this.queryPageList()
    },
    // 当前页
    currentChangeHandle (val) {
      this.pageIndex = val
      this.queryPageList()
    }
  }
}
</script>
<style scoped>
.content {
  max-height: 100vh;
  display: flex;
}
.m-form-box {
  margin: 20px;
  width: 20%;
}
.m-table-box {
  /* margin: 20px; */
  width: 78%;
}
.u-null {
  height: 300px;
  font-size: 15px;
}
</style>
